﻿
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sproc_SMS_CheckUpdate_V2]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[sproc_SMS_CheckUpdate_V2];
GO
CREATE PROCEDURE [dbo].[sproc_SMS_CheckUpdate_V2]
    @SessionID		nvarchar(100),
    @Username		nvarchar(50),
    @ActiveNodeID	int,
    @ReturnID		int OUTPUT,
    @NewMsgFlag		bit OUTPUT
/*

===================================================
功能:
    1.更新activetime         
    2.判断sessionid            
    3.删除5分钟内未活动人
    4.拿到最新在线人数得到在线人数
参数:
    @SessionID  Session码
    @Username  用户名
        
返回值:
     -1 此用户已经不该在线
     =>0 在线人数
===================================================

*/
AS
BEGIN

SET NOCOUNT ON

--判断是否在线
IF NOT EXISTS (SELECT 1 FROM dbo.UDS_Online WHERE AUTHKEY = @SessionID and Username = @Username)
BEGIN
    SET @ReturnID = -1
END
ELSE 
BEGIN    
    --判断是否有未读新的短消息
    IF NOT EXISTS (
        SELECT 1
        FROM dbo.UDS_SMS_Msg m INNER JOIN dbo.UDS_SMS_Receiver r ON m.ID = r.MsgID
        WHERE
            r.Receiver = @Username 
            and r.IsRead = /* new message */ 0
            and m.type = /* site message */ 1
    )
        SET @NewMsgFlag = 0
    ELSE
        SET @NewMsgFlag = 1
        
    --更新在线时间
    UPDATE dbo.UDS_Online SET ActiveTime = getdate(), ActiveNodeID = @ActiveNodeID WHERE Username = @Username;

    --删除五分钟钟未活动人员
    DELETE FROM dbo.UDS_Online WHERE DATEDIFF(n, ActiveTime, getdate()) > 5;

	-- Return the number of online users.
    SELECT @ReturnID = COUNT(1) FROM dbo.UDS_Online;
END

END
GO